﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Common.RabbitMQ
{
    /// <summary>
    /// rabbit配置
    /// </summary>
    public class RabbitConfig
    {
        private string _connection;
        /// <summary>
        /// 链接字符串（server=localhost;port=5672;uid=guest;password=guest;qos=1）
        /// </summary>
        public string Connection
        {
            get { return _connection; }
            set
            {
                SetFromConnectionString(value);
                _connection = value;
            }
        }
        private void SetFromConnectionString(string connection)
        {
            if (string.IsNullOrWhiteSpace(connection))
            {
                throw new ArgumentNullException("value", "RabbitMQ连接字符串有误");
            }
            string[] array = connection.Split(';');
            foreach (var item in array)
            {
                string[] kv = item.Split('=');
                if (kv == null || kv.Length != 2)
                {
                    throw new ArgumentException($"无效的RabbitMQ连接字符串[{item}]");
                }
                switch (kv[0].ToUpper())
                {
                    case "HOST":
                    case "SERVER":
                        Host = kv[1]; break;
                    case "PORT":
                        Port = Convert.ToInt32(kv[1]); break;
                    case "USERNAME":
                    case "UID":
                    case "USER":
                    case "USERID":
                        UserName = kv[1]; break;
                    case "PASSWORD":
                    case "PWD":
                        Password = kv[1]; break;
                    case "QOS":
                        Qos = Convert.ToUInt16(kv[1]); break;
                }
            }
        }
        internal ushort Qos { get; set; }
        /// <summary>
        /// 主机地址
        /// </summary>
        internal string Host { get; set; }
        /// <summary>
        /// 端口，默认 5672
        /// </summary>
        internal int Port { get; set; } = 5672;
        /// <summary>
        /// 账号
        /// </summary>
        internal string UserName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        internal string Password { get; set; }
        /// <summary>
        /// 重试次数（当消息处理失败次数大于此值会转到死信队列，不再处理）
        /// </summary>
        public int RetryTimes { get; set; }
        /// <summary>
        /// 重试间隔时间，不得小于10秒
        /// </summary>
        public TimeSpan RetryInterval { get; set; }
    }

}
